package com.amigo;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.widget.SwipeRefreshLayout;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.TextView;

import com.amigo.helper.Constants;
import com.amigo.helper.JsonFileUtility;
import com.amigo.helper.ServiceHandler;
import com.amigo.views.SwipeRefreshHintLayout;
import com.amigo.views.adapter.AmigoListViewAdapter;

public class Amigos extends Activity {

	private  SwipeRefreshLayout swipeView ;
	ListView list;
    AmigoListViewAdapter adapter;
    private String url = Constants.base_url + "friends" ; 
    private TextView empty_view ; 
   // private Boolean Success ; 
    private ArrayList<HashMap<String, String>> AmigosList;
    
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		this.requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.activity_amigos);

		swipeView = (SwipeRefreshLayout) findViewById(R.id.swipe);
		swipeView.setEnabled(false);
		SwipeRefreshHintLayout mSwipeRefreshHintLayout = (SwipeRefreshHintLayout) findViewById(R.id.swipe_hint);
		mSwipeRefreshHintLayout.setSwipeLayoutTarget(swipeView);
		swipeView.setColorSchemeColors(getResources().getColor(R.color.theme_secondary), getResources().getColor(R.color.white),getResources().getColor(R.color.theme_secondary), getResources().getColor(R.color.theme_background));
		swipeView.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
			
			@Override
			public void onRefresh() {
				
				new FetchAmigosTask().execute();				
			}
		});
		
		
		 AmigosList = new ArrayList<HashMap<String, String>>();
		 empty_view = (TextView) findViewById(R.id.empty_view);
		 empty_view.setVisibility(View.GONE);
		
		 new FetchAmigosTask().execute();
		 
		 list=(ListView)findViewById(R.id.list_amigos);
		 
		
	        // Getting adapter by passing xml data ArrayList
	        adapter=new AmigoListViewAdapter(this, AmigosList);
	        list.setAdapter(adapter);
	        list.setOnScrollListener(new AbsListView.OnScrollListener() {
		        @Override
		        public void onScrollStateChanged(AbsListView absListView, int i) {
		 
		        }
		 
		        @Override
		        public void onScroll(AbsListView absListView, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
		        	if (visibleItemCount > 0) {
						if (firstVisibleItem == 0) {

							if (list.getChildAt(0).getTop() == 0)
								swipeView.setEnabled(true);

							else
								swipeView.setEnabled(false);

						} else
							swipeView.setEnabled(false);
					}
		        }
		    });
	        
	        
	        list.setOnItemClickListener(new AdapterView.OnItemClickListener() {

				@Override
				public void onItemClick(AdapterView<?> arg0, View arg1,
						int position, long arg3) {
					
					HashMap<String, String> item = new HashMap<String, String>();
			        
			        item = AmigosList.get(position);
			        Intent i = new Intent (Amigos.this , Profile.class);
			        i.putExtra("user_from_amigos", item.get("user_object"));
			        startActivity(i);
			        finish();
			       
					
				}
			});
	        
	       
	        

	}
	private class FetchAmigosTask extends AsyncTask<Void, Void, Void>
	{
		
		@Override
		protected void onPreExecute() {
			AmigosList.clear();
			empty_view.setVisibility(View.INVISIBLE);
			super.onPreExecute();
		}
		
		@Override
		protected Void doInBackground(Void... args) {
			ServiceHandler sh = new ServiceHandler();
			List<NameValuePair> params = new ArrayList<NameValuePair>();
			params.add(new BasicNameValuePair("userId", JsonFileUtility.ReadJsonData(Constants.TAG_UserGUID)));
			

			// Making a request to url and getting response
			String jsonStr = sh.makeServiceCall(url,
					ServiceHandler.POST, params);

			Log.d("Response: ", "> " + jsonStr);

			if (jsonStr != null) {
				String dp = "init"; 
				try {
					JSONArray amigos = new JSONArray(jsonStr);
					for (int i =0 ; i < amigos.length() ; i++)
					{
						JSONObject amigo = amigos.getJSONObject(i);
						String name = amigo.getString("name");
						String location = amigo.getString("location");
						
						if (amigo.opt("profile_images") instanceof Boolean) {
							Log.d("STATUS", "no-dp");
							dp= "init" ;
						}
						else{
							JSONArray images = amigo.getJSONArray("profile_images");
							JSONObject first_image = images.getJSONObject(0);
							dp = first_image.getString("image_url");
						}
						
						
						HashMap<String, String> map = new HashMap<String, String>();
						
						map.put("user_name", name);
						map.put("user_location", location);
						map.put("image_url", dp);
						map.put("user_object" , amigo.toString());
						
						AmigosList.add(map);
						
					}
					
					
					
				} catch (JSONException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			
			}

			return null;
		}
		
		@Override
		protected void onPostExecute(Void result) {
			super.onPostExecute(result);
			if (swipeView.isRefreshing())
			{
				swipeView.setRefreshing(false);
			}
			if(AmigosList.size() > 0)
			{
			adapter.notifyDataSetChanged();
			list.setAdapter(adapter);
			}
			else if (AmigosList.size() == 0)
			{
				adapter.notifyDataSetChanged();
				list.setAdapter(adapter);
				empty_view.setVisibility(View.VISIBLE);
				
			}
			
			
		}
	}
	public void prev(View v ){
		startActivity(new Intent (Amigos.this , Dashboard.class));
		finish();
	}
	@Override
	public void onBackPressed() {
		
	}
	}
